library(clusterProfiler)
library(ggplot2)
library(enrichplot)
library(readxl)
library(plotly)
library(RColorBrewer)
color = colorRampPalette(rev(brewer.pal(n = 7, name =
                                          "RdYlBu")))(100)






files=c('./data/crispr/Molm13_MCL1i_DMSO_Day16.gene_summary.txt',
        './data/crispr/Molm13_combo_DMSO_Day16.gene_summary.txt',
        './data/crispr/VA_DMSO_Day16.gene_summary.txt',
        './data/crispr/Ven_DMSO_Day16.gene_summary.txt',
        './data/crispr/Aza_DMSO_Day16.gene_summary.txt')
axis_names=matrix(c('MCL1i lfc','MCL1i & Ven lfc','MCL1i lfc','Ven & Aza lfc','MCL1i & Ven lfc','Ven & Aza lfc',
                    'Ven lfc','MCL1i & Ven lfc'),2,4)
comparisons=matrix(c(1,2,1,3,2,3,4,2),2,4)

totdata=list()
for (kk in 1:length(files)) {
  temp=read.csv(files[kk],header=T,sep='\t',stringsAsFactors = F,check.names = T)
  totdata[[kk]]=temp
}


####3d plots

d1=totdata[[1]]
d2=totdata[[2]]
d3=totdata[[3]]

d1$id[d1$id=='5-Mar']='MARCH5'
d2$id[d2$id=='5-Mar']='MARCH5'
d3$id[d3$id=='5-Mar']='MARCH5'
genes=intersect(intersect(d1$id,d2$id),d3$id)
d1=d1[match(genes,d1$id),]
d2=d2[match(genes,d2$id),]
d3=d3[match(genes,d3$id),]
for (ii in 1:nrow(d1)) {
  if (d1$neg.lfc[ii]>=0)
    d1[ii,3:8]=d1[ii,9:14]
  
  if (d2$neg.lfc[ii]>=0)
    d2[ii,3:8]=d2[ii,9:14]
  if (d3$neg.lfc[ii]>=0)
    d3[ii,3:8]=d3[ii,9:14]
}
genes=union(union(d1$id[d1[,7]>=3],d2$id[d2[,7]>=3]),d3$id[d3[,7]>=3])

d1=d1[match(genes,d1$id),1:8]

d2=d2[match(genes,d2$id),1:8]
d3=d3[match(genes,d3$id),1:8]
plotdata=d1

plotdata[,2]=d1$neg.lfc
plotdata[,3]=d2$neg.lfc
plotdata[,4]=d3$neg.lfc
plotdata[,5]=d1$neg.p.value
plotdata[,6]=d2$neg.p.value
plotdata[,7]=d3$neg.p.value
plotdata[,8]=-log10((d1[,4]*d2[,4]*d3[,4])^1/3)
plotdata[,9]=0
plotdata[plotdata[,5]<0.05,9]=1
plotdata[plotdata[,6]<0.05,9]=2
plotdata[plotdata[,7]<0.05,9]=3
plotdata[plotdata[,5]<0.05 & plotdata[,6]<0.05 & plotdata[,7]<0.05,9]=4

names(plotdata)=c('id','MCL1i_lfc','MCL1i_Ven_lfc','VA_lfc','Pval1','Pval2','Pval3','Pval_comb','significance')
plotdata$significance=factor(plotdata$significance,levels=c(0,1,2,3,4),labels=c('not sig','MCL1i_sig','MCL1i_Ven_sig','VA_sig','All_Sig'))
plotdata=plotdata[,1:9]
temp=plotdata
getlabel <- function(x) {
  for (i in 1:length(ind))
    if (!is.na(as.numeric(x[ind[i]])))
      x[ind[i]]=round(as.numeric(x[ind[i]]),2)
  return(paste('</br>',paste(names(temp)[ind],x[ind],sep=':',collapse='</br>'),sep='',collapse='') )}
ind=1:8
plotdata$label=apply(plotdata,1,getlabel)


p1=plot_ly(plotdata,x=~MCL1i_lfc,y=~MCL1i_Ven_lfc,z=~VA_lfc,color=~log2(Pval_comb),marker=list(size=4),
           type='scatter3d',colors=rev(brewer.pal(n = 11, name = "RdYlBu")),text=~label, mode='markers',hoverinfo = c('text'))



filename=paste0('./figures/Figure1_DE.html')
htmlwidgets::saveWidget(as.widget(p1), file =filename)

tx  <- readLines(filename)
tx2  <- gsub(pattern = "&lt;", replace = "<", tx)
writeLines(tx2, con=filename)

